import React, { useState } from 'react'
import { useHistory } from 'react-router-dom';
import cookie from 'react-cookies';
import cn from 'classnames'
import { uploadProductLicenseNoToken } from '~/API/index'
import {Message, Button, Dialog, Upload, Loading} from '@knownsec/react-component'
import s from './style.module.css'
import i from '@/common.module.css'
import { getErrorMessage } from '@/common/constant';

export default function UploadCertificate() {
  const history = useHistory();
  const pathurl = history.location?.pathname;
  const flag = pathurl.split('?')[1] || '暂无';
  const [file, setFile] = useState('')
  const [visible, setVisible] = useState(false)
  const [showLoading, setLoading] = useState(false)
  const [userInfo, setUserInfo] = useState({
    username: '',
    password: ''
  })
  const upCert = () => {
    const data = new FormData()
    data.append('file', file)
    setLoading(true)
    uploadProductLicenseNoToken('POST', data).then(res => {
        setLoading(false)
        if(res.status === 'success'){
            Message.show({ type: 'success', message: res.message })
            const users = res.data || ''
            if(users){
                setVisible(true)
                setUserInfo(users)
            }else{
                window.location.href = '#/login'
            }
        }
    }).catch(err => {
        Message.show({ type: 'error', message: getErrorMessage(err,'data')})
        setLoading(false);
    })
  }
  const uploadFile = file => {
    setFile(file)
    return false
  }
  const copyText = () => {
    const copyEle = document.querySelector('#copy')
    const range = document.createRange()
    window.getSelection().removeAllRanges()
    range.selectNode(copyEle)
    window.getSelection().addRange(range)
    const copyStatus = document.execCommand("Copy")
    if (copyStatus) {
      Message.show({ type: 'success', message: '复制成功' })
    } else {
      Message.show({ type: 'error', message: '复制失败' })
    }
    window.getSelection().removeAllRanges()
  }
  return (
    <div className={cn(i.w100p, i.h100p, s.bgs, i.pa)}>
    <Loading show={showLoading} label="证书上传中..." />
      <div className={cn(i.pa, s.box)}>
        <p className={cn(i.pt30, i.fs16)}>请先导入证书</p>
        <div className={s.inner}>
          <div className={cn(i.pt20, i.pl20)}>
            <span>设备标识</span>
            <span className={cn(i.ml30)}>{flag}</span>
          </div>
          <div className={cn(i.pt20, i.pl20, i.df, i.aic)}>
            <span>证&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;书</span>
            <Upload
              maxCount={1}
              beforeUpload={uploadFile}
              showUploadList={false}>
              <span className={cn(s.btns, i.ml30, i.cp)}>点击上传".lic"格式文件</span>
            </Upload>
          </div>
          <div className={s.filename}>
            {file?.name && <span className={s.hui}></span>}
            <span>{file?.name}</span>
          </div>
        </div>
        <div className={cn(i.pt30, i.tac)}>
          <span className={cn(s.oks, i.cp)} onClick={upCert}>确定</span>
        </div>
      </div>
      <Dialog
        className={s.w400}
        title="初始通行证"
        cancelText=""
        confirmText=""
        visible={visible}
      >
        <div className={i.p20}>
          <p>用户名：{userInfo.username}</p>
          <p className={i.mt15}>
            <span>密码：</span>
            <span id="copy" className={i.mr10}>{userInfo.password}</span>
            <span className={cn(i.mainColor, i.cp)} onClick={copyText}>一键复制</span>
          </p>
          <div className={cn(i.tac, i.mt20)}>
            <Button onClick={() => {
              setFile('')
              setVisible(false)
            }}>重新上传</Button>
            <Button type="primary" className={i.ml20} onClick={() => {
              window.location.href = '#/login'
            }}>去登录</Button>
          </div>
        </div>
      </Dialog>
    </div>
  )
}
